package com.kuang.bq;

import java.util.Collection;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

public class Test {
    public static void main(String[] args) throws InterruptedException {
        test4();

    }
    /**
     * 抛出异常
     */
    public static void test1(){
        //队列的大小
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);

        System.out.println(blockingQueue.add("a"));
        System.out.println(blockingQueue.add("b"));
        System.out.println(blockingQueue.add("c"));
        System.out.println("=======================================");
        //Exception in thread "main" java.lang.IllegalStateException: Queue full  会抛异常
//        System.out.println(blockingQueue.add("d"));
        System.out.println(blockingQueue.peek());
        System.out.println(blockingQueue.remove());
        System.out.println(blockingQueue.remove());
        System.out.println(blockingQueue.remove());
        //抛出异常
        //System.out.println(blockingQueue.remove());
    }

    /**
     * 有返回值没有异常
     */
    public static void test2(){
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
        System.out.println(blockingQueue.offer("a"));
        System.out.println(blockingQueue.offer("b"));
        System.out.println(blockingQueue.offer("c"));
        //返回false 不抛出异常
//        System.out.println(blockingQueue.offer("d"));

        System.out.println(blockingQueue.element());//查看队首的元素是谁
        System.out.println("====================================");
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
        //会返回null值
        System.out.println(blockingQueue.poll());


    }

    /**
     * 等待,阻塞(一直)
     */
    public static void test3() throws InterruptedException {
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);

        //一直阻塞
        blockingQueue.put("a");
        blockingQueue.put("b");
        blockingQueue.put("c");
//        blockingQueue.put("d");

        System.out.println(blockingQueue.take());
        System.out.println(blockingQueue.take());
        System.out.println(blockingQueue.take());
        //多取一个会阻塞在这里 一直等待
        System.out.println(blockingQueue.take());
    }





    /**
     * 等待,阻塞(等待超时 )
     */
    public static void test4() throws InterruptedException {
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);

        blockingQueue.offer("a");
        blockingQueue.offer("b");
        blockingQueue.offer("c");
        //blockingQueue.offer("d",2, TimeUnit.SECONDS);

        System.out.println("=================================");

        System.out.println(blockingQueue.poll(2, TimeUnit.SECONDS));
        System.out.println(blockingQueue.poll(2, TimeUnit.SECONDS));
        System.out.println(blockingQueue.poll(2, TimeUnit.SECONDS));
        System.out.println(blockingQueue.poll(2, TimeUnit.SECONDS));
    }
}
